import { IFeidaoAiBrowserComponent } from '@feidao/web/interfaces';
import client_login from '@feidao/web/atom/browser/msg/user-login-with-captcha';
import set_user from '@feidao/web/atom/browser/storage/put';
import { login, login_phone } from './config';
import error from '@feidao/web/atom/browser/msgbox/error';
// import a001 from './a001';
export default async function a004(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
	const correctu = /^[\w*\_*]{6,15}$/; // 用户名格式错误（允许6-15位字母、数字、下划线）
	// let correctp = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,21}$/; //密码格式错误（允许6-21字母和数字组成，不能是纯数字或纯英文）;
	const user_name = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id="user_name"]');
	if (!user_name.value) {
		error('用户名不能为空！');
		return;
	} else if (!user_name.value.match(correctu)) {
		error('用户名格式错误（允许6-15位字母、数字、下划线）');
		return;
	}
	const user_pwd = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id="user_pwd"]');
	if (!user_pwd.value) {
		error('密码不能为空！');
		return;
	}
	// else if (!user_pwd.value.match(correctp)) {
	// 	error('密码格式错误（允许6-21字母和数字组成，不能是纯数字或纯英文）');
	// 	return;
	// }
	const pic_verification = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id="pic_verification"]');
	if (!pic_verification.value) {
		error('验证码不能为空！');
		return;
	}
	try {
		// 调用登录的通用服务
		// get-address-byip
		const res = await client_login(login, user_name.value, user_pwd.value, pic_verification.value);
		await set_user('user', res);
		// 跳转到其他页面
		const backurl = fd.data.params.backurl;
		if (backurl) {
			window.location.href = decodeURIComponent(backurl);
		} else {
			window.location.href = 'home.html';
		}
	} catch (err) {

		try {
			// 调用登录的通用服务
			// get-address-byip
			const res = await client_login(login_phone, user_name.value, user_pwd.value, pic_verification.value);

			await set_user('user', res);
			// 跳转到其他页面

			const backurl = fd.data.params.backurl;

			if (backurl) {
				window.location.href = decodeURIComponent(backurl);
			} else {
				window.location.href = 'home.html';
			}
		} catch (err1) {
			error(err);
			const img = fd.data.node.querySelector('[data-feidao-id="captcha"]') as HTMLImageElement;
			img.click();
			pic_verification.value = '';
		}

	}
}

